'use strict';

const Controller = require('egg').Controller;

class ArticleController extends Controller {
    async getData() {
        // 从数据库接口获取富文本数据
        const dbData = await this.ctx.service.db.getData();
    
        // 创建 wangEditor 编辑器实例
        const editor = this.app.wangEditor.createEditor('editor-container', {
          // 配置更多参数
        });
    
        // 将数据库中的数据赋值给编辑器
        editor.txt.html(dbData.content);
    
        // 返回数据给前端
        this.ctx.body = {
          content: dbData.content
        };
      }
    // 列表
    async index() {
        const { ctx, app } = this;

        let data = await ctx.page('Article', {}, {
            include: [
                {
                    model: app.model.Category,
                }]
        })
        data = JSON.parse(JSON.stringify(data))
        console.log(data)

        await ctx.renderTemplate({
            title: "文章列表",
            tempType: "table",
            table: {
                // 按钮
                buttons: {
                    // 新增操作
                    add: "/admin/article/create"
                },
                // 表头
                columns: [{
                    title: "ID",
                    fixed: 'center',
                    key: "id"
                }, {
                    title: "标题",
                    fixed: 'left',
                    key: "title"
                }, {
                    title: "所属分类",
                    fixed: 'center',
                    render(item) {
                        return `
                    <h2 class="table-avatar">
                        ${item.category.title}
                    </h2>
                    `
                    }
                }, {
                    title: "创建时间",
                    fixed: 'center',
                    width: 180,
                    key: "created_time"
                }, {
                    title: "排序",
                    fixed: 'center',
                    key: "order"
                }, {
                    title: "操作",
                    width: 200,
                    fixed: 'center',
                    action: {
                        edit: function (id) {
                            return `/admin/article/edit/${id}`
                        },
                        delete: function (id) {
                            return `/admin/article/delete/${id}`
                        },
                    }
                }]
            },
            data
        })
    }
    // 创建文章表单
    async create() {
        const { ctx, app } = this;
        let cateo = await app.model.Category.findAll()
        cateo = JSON.parse(JSON.stringify(cateo))
        console.log(cateo)
        await ctx.renderTemplate({
            // 页面标题
            title: "添加文章",
            // 模板类型 form表单，table表格分页
            tempType: "form",
            // 表单配置
            form: {
                // 提交地址
                action: "/admin/article",
                // 字段配置
                fields: [{
                    label: "分类",
                    type: "select",
                    name: "cate_id",
                    field: "title",
                    options: cateo,
                    placeholder: "所属分类"
                }, {
                    label: "标题",
                    type: "text",
                    name: "title",
                    placeholder: "标题"
                }, {
                    label: "缩略图",
                    type: "file",
                    name: "thumb",
                    placeholder: "缩略图"
                }, {
                    label: "来源",
                    type: "text",
                    name: "source",
                    placeholder: "来源"
                }, {
                    label: "作者",
                    type: "text",
                    name: "auther",
                    placeholder: "作者"
                }, {
                    label: "关键词",
                    type: "text",
                    name: "keywords",
                    placeholder: "关键词"
                }, {
                    label: "描述",
                    type: "text",
                    name: "description",
                    placeholder: "标题"
                }, {
                    label: "推荐位",
                    type: "select",
                    name: "posid",
                    field: "title",
                    options: [{
                        title: '焦点',
                        id: 1
                    }, {
                        title: '头条',
                        id: 2
                    }, {
                        title: '推荐',
                        id: 3
                    }],
                    placeholder: "推荐位"
                }, {
                    label: "发布时间",
                    type: "date",
                    name: "created_time",
                    placeholder: "发布时间"
                }, {
                    label: "内容",
                    type: "article",
                    name: "content",
                    placeholder: "内容"
                }]
            },
            // 新增成功跳转路径
            successUrl: "/admin/article"
        });
    }

    // 创建文章逻辑
    async save() {
        const { ctx, app } = this;

        ctx.validate({
            cate_id: {
                type: "int",
                required: true,
                desc: "分类"
            },
            title: {
                type: "string",
                required: true,
                desc: "标题"
            },
            thumb: {
                type: "string",
                required: false,
                desc: "缩略图"
            },
            source: {
                type: "string",
                required: false,
                desc: "来源"
            },
            auther: {
                type: "string",
                required: false,
                desc: "作者"
            },
            keywords: {
                type: "string",
                required: false,
                desc: "关键词"
            },
            description: {
                type: "string",
                required: false,
                desc: "描述"
            },
            posid: {
                type: "int",
                required: false,
                desc: "推荐位"
            },
            created_time: {
                type: "string",
                required: false,
                desc: "发布时间"
            },
            content: {
                type: "string",
                required: false,
                desc: "内容"
            },
        })

        let { cate_id, title, thumb, source, auther, keywords, description, posid, created_time, content } = ctx.request.body;

        if (await app.model.Article.findOne({
            where: {
                title
            }
        })) {
            return ctx.apiFail('该文章已存在');
        }

        let article = await app.model.Article.create({
            cate_id, title, thumb, source, auther, keywords, description, posid, created_time, content
        })

        ctx.apiSuccess(article)
    }

    // 编辑表单页
    async edit() {
        const { ctx, app } = this
        let cateo = await app.model.Category.findAll()
        cateo = JSON.parse(JSON.stringify(cateo))
        const id = ctx.params.id

        let data = await app.model.Article.findByPk(id);
        if (!data) {
            return await ctx.pageFail('该记录不存在')
        }

        data = JSON.parse(JSON.stringify(data))
        await ctx.renderTemplate({
            id,
            title: "修改文章",
            tempType: "form",
            form: {
                // 提交地址
                action: "/admin/article/" + id,
                // 字段配置
                fields: [{
                    label: "分类",
                    type: "select",
                    name: "cate_id",
                    field: "title",
                    options: cateo,
                    placeholder: "所属分类"
                }, {
                    label: "标题",
                    type: "text",
                    name: "title",
                    placeholder: "标题"
                }, {
                    label: "缩略图",
                    type: "file",
                    name: "thumb",
                    placeholder: "缩略图"
                }, {
                    label: "来源",
                    type: "text",
                    name: "source",
                    placeholder: "来源"
                }, {
                    label: "作者",
                    type: "text",
                    name: "auther",
                    placeholder: "作者"
                }, {
                    label: "关键词",
                    type: "text",
                    name: "keywords",
                    placeholder: "关键词"
                }, {
                    label: "描述",
                    type: "text",
                    name: "description",
                    placeholder: "标题"
                }, {
                    label: "推荐位",
                    type: "select",
                    name: "posid",
                    field: "title",
                    options: [{
                        title: '焦点',
                        id: 1
                    }, {
                        title: '头条',
                        id: 2
                    }, {
                        title: '推荐',
                        id: 3
                    }],
                    placeholder: "推荐位"
                }, {
                    label: "发布时间",
                    type: "date",
                    name: "created_time",
                    placeholder: "发布时间"
                }, {
                    label: "内容",
                    type: "article",
                    name: "content",
                    placeholder: "内容"
                }],
                // 默认值
                data
            },
            // 修改成功跳转路径
            successUrl: "/admin/article"
        })
    }

    // 更新逻辑
    async update() {
        const { ctx, app } = this;
        ctx.validate({
            id: {
                type: "int",
                required: true
            },
            cate_id: {
                type: "int",
                required: true,
                desc: "分类"
            },
            title: {
                type: "string",
                required: true,
                desc: "标题"
            },
            thumb: {
                type: "string",
                required: false,
                desc: "缩略图"
            },
            source: {
                type: "string",
                required: false,
                desc: "来源"
            },
            auther: {
                type: "string",
                required: false,
                desc: "作者"
            },
            keywords: {
                type: "string",
                required: false,
                desc: "关键词"
            },
            description: {
                type: "string",
                required: false,
                desc: "描述"
            },
            posid: {
                type: "int",
                required: false,
                desc: "推荐位"
            },
            created_time: {
                type: "string",
                required: false,
                desc: "发布时间"
            },
            content: {
                type: "string",
                required: false,
                desc: "内容"
            },
        })

        let id = ctx.params.id
        let { cate_id, title, thumb, source, auther, keywords, description, posid, created_time, content } = ctx.request.body

        let article = await app.model.Article.findOne({
            where: {
                id
            }
        })
        if (!article) {
            return ctx.apiFail('该记录不存在')
        }

        const Op = app.Sequelize.Op

        article.cate_id = cate_id
        article.title = title
        article.thumb = thumb
        article.source = source
        article.auther = auther
        article.keywords = keywords
        article.description = description
        article.posid = posid
        article.created_time = created_time
        article.content = content

        ctx.apiSuccess(await article.save())

    }

    // 删除
    async delete() {
        const { ctx, app } = this;
        const id = ctx.params.id
        await app.model.Article.destroy({
            where: {
                id
            }
        })
        ctx.toast('删除成功', 'success')
        ctx.redirect('/admin/article')
    }
}

module.exports = ArticleController;
